package testndk.testservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import testndk.testservice.service.EventService;
public class EventActivity extends Activity {

	private boolean mIsBind;
	private Button startBtn = null;
	private Button stopBtn = null;
	private TextView mTextView = null;


	private Intent intent = null;
	private ProgressBar mProgressBar = null;
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 21:
				int curLoad = msg.arg1;
				mTextView.setText(curLoad+"%");
				mProgressBar.setProgress(curLoad);
				break;

			default:
				break;
			}
		}
	};
	private EventBus eventBus;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
		//注册EventBus
		eventBus = EventBus.getDefault();
		eventBus.register(this);

        intent = new Intent(this,EventService.class);
        mProgressBar = (ProgressBar)findViewById(R.id.myProgressBar);
        mProgressBar.setMax(100);
        mTextView = (TextView)findViewById(R.id.loading_Tv);
        startBtn = (Button)findViewById(R.id.start_Btn);
        stopBtn = (Button)findViewById(R.id.stop_Btn);
        startBtn.setOnClickListener(new ButtonClickListener());
        stopBtn.setOnClickListener(new ButtonClickListener());
        
    }


	class ButtonClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (startBtn == v) {
				startService(intent);
			} else if (stopBtn == v) {
				if(mIsBind){
					stopService(intent);
					mIsBind = false;
				}
			}
		}
	}

	/**
	 * 接收服务端的数据
	 * @param temp
	 */
	@Subscriber(tag = EventService.EVNET_TAG)
	private  void getEventData(int temp){
		Message message = mHandler.obtainMessage();
		message.what = 21;
		message.arg1 = temp;
		mHandler.sendMessage(message);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		eventBus.unregister(this);
	}
}